package com.czy.moudle.exception.service.impl;

import com.alibaba.fastjson.JSON;
import com.czy.moudle.exception.domain.BaseExceptation;
import com.czy.moudle.exception.service.WebExceptionProcess;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/***
 * @author 陈致远
 * @date 2016/11/29
 */
@Service("webExceptionProcess")
public class WebExceptionProcessImpl implements WebExceptionProcess {
    @Override
    public ModelAndView process(HttpServletRequest request, HttpServletResponse response, BaseExceptation be) {
        Map<String, Object> exInfo = ex2Map(be);

        String requestType = request.getHeader("X-Requested-With");

        if (StringUtils.equalsIgnoreCase("XMLHttpRequest", requestType)) {
            //ajax请求
            String json = JSON.toJSONString(exInfo);
            try {
                response.getWriter().write(json);
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }else{//其他请求
            ModelAndView md = new ModelAndView("error");
            md.addObject("exInfo", exInfo);
            return md;
        }
    }

    /**
     * BaseException转换为Map<String,Object>
     * @param be BaseException对象
     * @return BaseException自定义属性组成的键值对集合
     */
    private Map<String, Object> ex2Map(BaseExceptation be) {
        Map<String, Object> exInfo = new HashMap<>();
        exInfo.put("errKey", be.getErrKey());
        exInfo.put("errCode", be.getErrCode());
        exInfo.put("content", be.getContent());
        exInfo.put("type", be.getType());
        exInfo.put("level", be.getLevel());
        exInfo.put("msg", be.getMessage());
        return exInfo;
    }
}
